package bfh._4_semester.simpleCMS.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import bfh._4_semester.simpleCMS.client.DBConnection;
import bfh._4_semester.simpleCMS.client.User;

public class MySQLConnection extends RemoteServiceServlet implements
		DBConnection {
	private Connection conn = null;
	private String status;
	private String url = "jdbc:mysql://sspaeti.mysql.db.hostpoint.ch:3306/sspaeti_bfhcms";
	private String user = "sspaeti_bfhcms";
	private String pass = "sspaeti_bfhcms";

	public MySQLConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(url, user, pass);
		} catch (Exception e) {
			System.out.println("Couldn't Connect to the DB");
			e.printStackTrace();
		}
	}

	public void closeMySQLConnection(){
		
		try {
			//Close connection
			conn.close();
		} catch (SQLException e) {
			System.out.println("Couldn't close the DB Connection");
			e.printStackTrace();
		}
		System.out.println("Disconnected from database");
	}
	
	public User authenticateUser(String user, String pass) {

		User user2 = null;
		try {
			PreparedStatement ps = conn
					.prepareStatement("select readonly * from user where username =\""
							+ user + "\" AND " + "password = \"" + pass + "\"");
			ResultSet result = ps.executeQuery();
			while (result.next()) {
				user2 = new User(result.getString(1), result.getString(2));
			}
			result.close();
			ps.close();
		} catch (SQLException sqle) {
			System.out.println("SQL Error");
		}
		return user2;
	}
}